<?php

/**
 * Ares ApiController class file
 * @author xingkun
 * @date 2014/11/07
 */
class ApiController extends ApiBaseController {

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'BeforeApiCall',
        );
    }

    /**
     *  访问API前统一参数过滤器
     *  
     * @param  object $filterChain 过滤器链
     * @access public
     * @return void
     */
    public function filterBeforeApiCall($filterChain) {
        // remove cookie from request, 
        // Note: after php5.3 set by request_order = "GP" in php.ini
        $_REQUEST = array_diff_key($_REQUEST, $_COOKIE);

        // 验证系统级参数
        // 测试模式下，不验证系统级参数
        if (!isset($_REQUEST['test'])) {
            $this->validateSysParams($_REQUEST);
        }

        // 验证API级参数
        $this->validateApiParams($_REQUEST);

        //参数$filterChain就是执行该filter的action实例，调用$filterChain->run()其实就是执行该action了。
        $filterChain->run();
    }

    /*     * ************* api functions ************** */

    /**
     * 获取APP信息
     * @return void
     */
    public function actionGetAppInfo() {
        $appKey = AresApiUtil::generateAppKey();
        $appSecret = AresApiUtil::generateAppSecret($appKey);
        $result = array(
            'appKey' => $appKey,
            'appSecret' => $appSecret,
        );
        // send result
        $this->sendResult($result, 'app');
    }

    /**
     * 获取访问令牌
     *
     * @access public
     * @return void
     */
    public function actionGetAccessToken() {
        // preprocess
        $accessToken = session_id();

        $data = array(
            'accessToken' => $accessToken,
        );
        // send result
        $this->sendResult($data);
    }

    /*     * ****************** 个人中心 ******************* */

    /**
     * 登录
     * 
     * @return void
     */
    public function actionLogin() {
        // preprocess parameters
        $username = $this->getString($_REQUEST['mobileNo']);
        $mode = $this->getString($_REQUEST['mode']); // 1. email 2. phone 3. nickname
        $password = $this->getString($_REQUEST['pwd']);

        // Find the user
        switch ($mode) {
            case '1':
                $customerEmail = strtolower($username);
                $customer = Customer::model()->find('LOWER(customer_email)=:customer_email', array('customer_email' => $customerEmail));
                break;
            case '2':
                $customerPhone = $username;
                $customer = Customer::model()->find('customer_mobile=:customer_mobile', array('customer_mobile' => $customerPhone));
                break;
            case '3':
                $customerNickname = $username;
                $customer = Customer::model()->find('customer_nickname=:customer_nickname', array('customer_nickname' => $customerNickname));
                break;
            default:
                $customerEmail = strtolower($username);
                $customer = Customer::model()->find('LOWER(customer_email)=:customer_email', array('customer_email' => $customerEmail));
                break;
        }
        // validate password
        if ($customer === null) {
            // send error
            $this->sendApiError('1001011');
        } elseif (!AresUtil::validatePassword($password, $customer->customer_password, true)) {
            // send error
            $this->sendApiError('1001001');
        } else {
            // init session data
            $this->initSessionData($customer->customer_id);

            // has zhiyebao
            $arrSqlParams = array(
                'condition' => 't.customer_id=' . $customer->customer_id,
            );

            $data = array(
                'token' => Yii::app()->apiUser->token,
                'customer_id' => (string) Yii::app()->apiUser->customer_id,
                'nickName' => (string) $customer->customer_nickname,
                'mobile' => (string) $customer->customer_mobile,
                'avatar' => "/upload/default/22400832721838835061.jpg",
            );
            // send result
            $this->sendResult($data);
        }
    }

    /**
     * 退出
     * 
     * @return void
     */
    public function actionLogout() {
        //get token
        $token = $this->getString($_REQUEST['token']);

        //查看当前登录状态是否有效
        $this->checkToken($token);

        //注销session
        //移去所有session变量
        Yii::app()->session->clear();
        //移去存储在服务器端的数据
        Yii::app()->session->destroy();
        //重新开启一个新的session，并将id返回给客户端
        Yii::app()->session->open();
        if (empty(Yii::app()->apiUser->customer_id)) {
            $status = 'success'; //成功
            $message = '退出成功';
        } else {
            $status = 'fail'; //失败
            $message = '退出失败，请重新操作';
        }

        $data = array(
            'status' => $status,
            'message' => $message,
            'accessToken' => Yii::app()->session->getSessionID(),
        );
        // send result
        $this->sendResult($data);
    }

    /**
     * 注册
     * 
     * @return void
     */
    public function actionRegister() {
        $mode = $this->getString($_REQUEST['mode']); // 1. email 2. phone 3. nickname
        $username = $this->getString($_REQUEST['mobileNo']);
        $password = $this->getString($_REQUEST['pwd']);
        $nickName = $this->getString('nickName');

        $customer = new Customer();
        //登录名
        switch ($mode) {
            case '1':
                $customer->customer_email = $username;
                break;
            case '2':
                $customer->customer_mobile = $username;
                // 客户端做了验证码
                $customer->is_mobile_actived = 1;
                break;
            case '3':
                $customer->customer_nickname = $username;
                break;
            default:
                break;
        }
        if ($mode == 2 && Customer::model()->find('customer_mobile=:customer_mobile', array(':customer_mobile' => $username))) {
            $status = 'fail';
            $message = '该手机号已注册，请勿重复注册';
            $result = array(
                'status' => $status,
                'message' => $message,
            );
            // add log
            AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'customer register', 'parameters' => $_REQUEST, 'response' => $result));

            // send result
            $this->sendResult($result);
        }

        //密码
        $customer->customer_password = AresUtil::encryptPassword($password, true);
        $customer->customer_nickname = $nickName; //AresUtil::generateRandomStr(16);
        if ($customer->insert()) {
            $status = 'success';
            $message = '注册成功';
        } else {
            $status = 'fail';
            $message = '注册失败，请重新注册';
        }

        $result = array(
            'status' => $status,
            'message' => $message,
        );

        // add log
        AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'customer register', 'parameters' => $_REQUEST, 'response' => $result));

        // send result
        $this->sendResult($result);
    }

    /**
     * 忘记密码
     * 
     * @return void
     * todo
     */
    public function actionForgetPwd() {
        //preprocess parameters
        $username = $this->getString($_REQUEST['username']);
        $mode = $this->getInt($_REQUEST['mode']); // 1. email 2. phone
        $new_password = $this->getString($_REQUEST['new_password']);

        // Find the user
        switch ($mode) {
            case '1':
                $customerEmail = strtolower($username);
                $objCustomer = Customer::model()->find('LOWER(customer_email)=:customer_email', array('customer_email' => $customerEmail));
                break;
            case '2':
                $customerPhone = $username;
                $objCustomer = Customer::model()->find('customer_mobile=:customer_mobile', array('customer_mobile' => $customerPhone));
                break;
            default:
                $customerEmail = strtolower($username);
                $customer = Customer::model()->find('LOWER(customer_email)=:customer_email', array('customer_email' => $customerEmail));
                break;
        }

        // 验证账号是否存在
        if ($objCustomer === null) {
            // send error
            $this->sendApiError('1001007', array('parameter' => $username));
        } else {
            // do nothing
        }

        // 设置新密码
        if ($mode == 2) { //mobile
            $objCustomer->customer_password = AresUtil::encryptPassword($new_password, true);
            $need_send_email = false;
        } elseif ($mode == 1) { //email
            $new_password = AresUtil::generateRandomStr(6);
            $objCustomer->customer_password = AresUtil::encryptPassword($new_password);
            $need_send_email = true;
        } else {
            $need_send_email = false;
        }

        // 更新为新密码
        if ($objCustomer->update()) {
            // add log
            AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'reset password success', 'parameters' => array(), 'response' => array()));
            $update_password_status = true;
            $status = 'success';
            $message = '密码修改成功';
        } else {
            // add log
            AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'reset password fail', 'parameters' => array(), 'response' => array()));
            $update_password_status = false;
            $status = 'fail';
            $message = '更新密码失败';
        }

        // 发送邮件
        if (($need_send_email == true) && ($update_password_status == true) && !empty($objCustomer->customer_email)) {
            // customer name
            if (!empty($objCustomer->customer_fullname)) {
                $customer_name = $objCustomer->customer_fullname;
            } else {
                $customer_name = $objCustomer->customer_email;
            }

            // mail setting
            $mail_to = $objCustomer->customer_email;
            $mail_subject = '找回密码';
            $mail_parameters = array(
                'EMAIL_TXT_CUSTOMER_NAME' => $customer_name,
                'EMAIL_TXT_NEW_PASSWORD' => $new_password,
            );
            $mail_template = 'email_template_password_forgotten';

            // init mailer
            $objMailer = new AresMailer($mail_template, $mail_parameters);
            //set properties
            $objMailer->setTo($mail_to);
            $objMailer->setSubject($mail_subject);

            // send
            $mailParams = array(
                'to' => $mail_to,
                'subject' => $mail_subject,
                'parameters' => $mail_parameters,
            );
            if ($objMailer->send()) {
                $status = 'success';
                $message = '新密码已经发送到您的邮箱，请及时修改密码！';
                $mailResult = array(
                    'mail_error' => 'success',
                );
                // add log
                AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'send mail success', 'parameters' => $mailParams, 'response' => $mailResult));
            } else {
                $status = 'fail';
                $message = '重置密码邮件发送失败，请重试';
                $mailResult = array(
                    'mail_error' => $objMailer->getError(),
                );
                // add log
                AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'send mail fail', 'parameters' => $mailParams, 'response' => $mailResult));
            }
        }

        $result = array(
            'status' => $status,
            'message' => $message,
        );

        // add log
        AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'forget password function result', 'parameters' => $_REQUEST, 'response' => $result));

        // send result
        $this->sendResult($result);
    }

    /**
     * 修改密码
     * 
     * @return void
     */
    public function actionChangePwd() {
        //preprocess parameters
        $token = $this->getString($_REQUEST['token']);
        $old_password = $this->getString($_REQUEST['old_password']);
        $new_password = $this->getString($_REQUEST['new_password']);
        $confirm_password = $this->getString($_REQUEST['confirm_password']);

        //查看当前登录状态是否有效
        $this->checkToken($token);

        //验证数据
        if ($old_password == $new_password) {
            // send error
            $this->sendApiError('1001008');
        }
        if ($new_password != $confirm_password) {
            // send error
            $this->sendApiError('1001009');
        }

        //取出个人ID
        $objCustomer = Customer::model()->findByPk(array('customer_id' => $_SESSION['customer_id']));
        if (!AresUtil::validatePassword($old_password, $objCustomer->customer_password, true)) {
            // send error
            $this->sendApiError('1001003');
        }

        //更新为新密码
        $objCustomer->customer_password = AresUtil::encryptPassword($new_password, true);
        if ($objCustomer->update()) {
            $status = 'success';
            $message = '修改密码成功，请使用新密码重新登录';
        } else {
            $status = 'fail';
            $message = '修改密码失败';
        }

        $result = array(
            'status' => $status,
            'message' => $message,
        );

        // add log
        AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'change password', 'parameters' => $_REQUEST, 'response' => $result));

        // send result
        $this->sendResult($result);
    }

    /**
     * 处理用户上传头像
     * @param string  token    用户登录后的session密钥
     * @param binary_data    二进制数据流
     * @return void
     */
    public function actionUploadPhoto() {
        //get token
        $token = $this->getString($_REQUEST['token']);

        //查看当前登录状态是否有效
        $this->checkToken($token);

        //取出个人ID
        $customer_id = $_SESSION['customer_id'];

        //二进制图片流
        //$imageUpload = new ApiImageUpload();                
        //$arrResult = $imageUpload->stream2Image();
        //图片上传
        $imageUpload = new ApiImageUpload();
        $arrResult = $imageUpload->formUpload('photo');

        // add log
        AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'save image from binary stream', 'parameters' => $_REQUEST, 'response' => $arrResult));

        if ($arrResult['status'] == false) {
            $this->sendApiError($arrResult['status']);
        } else {
            $customer = Customer::model()->findByPk(array('customer_id' => $customer_id));
            $customer->customer_avatar = $arrResult['url']; // 修改头像
            //更新
            if ($customer->update()) {
                $status = 'success'; //成功
                $message = '头像上传成功';
            } else {
                $status = 'fail'; //失败
                $message = '头像上传失败，请重新操作';
            }
            $result = array(
                'status' => $status,
                'message' => $message,
            );

            // add log
            AresLogManager::log_bi(array('logKey' => '[API][' . __METHOD__ . ']', 'desc' => 'save customer avatar photo', 'parameters' => $arrResult, 'response' => $result));

            // send result
            $this->sendResult($result);
        }
    }

    /**
     * 
     */
    public function actionAlbumRipples() {
        $picCell = array(
            'thumb' => array(
                'picId' => 1,
                'picUrl' => 'http://art.china.cn/car/images/attachement/jpg/site8/20100423/002564bb36d20d3b9a5312.jpg',
                'commentList' => array(
                    array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                )
            ),
            'picList' => array(
                array(
                    'picId' => 2,
                    'picUrl' => 'http://bizhi.zhuoku.com/2010/08/22/Morgan-EvaGT/Morgan-EvaGT09.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
                array(
                    'picId' => 3,
                    'picUrl' => 'http://pic20.nipic.com/20120506/3695685_100008655108_2.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
                array(
                    'picId' => 4,
                    'picUrl' => 'http://g.hiphotos.baidu.com/zhidao/pic/item/64380cd7912397dd172f19df5882b2b7d1a28793.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
                array(
                    'picId' => 5,
                    'picUrl' => 'http://pic3.nipic.com/20090520/2489240_222437074_2.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
                array(
                    'picId' => 6,
                    'picUrl' => 'http://img.taopic.com/uploads/allimg/111118/1901-11111PJR146.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
                array(
                    'picId' => 7,
                    'picUrl' => 'http://pic22.nipic.com/20120628/9146314_174122769187_2.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
                array(
                    'picId' => 8,
                    'picUrl' => 'http://www.c168c.com/images/attachement/jpg/site132/20110302/0016ecaae7b30ed8449e1c.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
                array(
                    'picId' => 9,
                    'picUrl' => 'http://pic9.nipic.com/20100910/668573_164813098586_2.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
                array(
                    'picId' => 10,
                    'picUrl' => 'http://bizhi.zhuoku.com/2009/10/13/Zagato/2010-Zagato-Perana-Z-One-006.jpg',
                    'commentList' => array(
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                        array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    )
                ),
            )
        );
        //声明基本对象
        $cell = array(
            'rippleId' => 0, //会变动
            'thumb' => array(
                'picId' => 1,
                'picUrl' => 'http://art.china.cn/car/images/attachement/jpg/site8/20100423/002564bb36d20d3b9a5312.jpg',
                'commentList' => array(
                    array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                    array('userId' => 1, 'userName' => '评论账户', 'content' => '这是个评论'),
                )
            ),
        );
        $pageSize = !empty($_REQUEST['pageSize']) ? $this->getInt($_REQUEST['pageSize']) : 10;
        $startRippleId = !empty($_REQUEST['startRippleId']) ? $this->getInt($_REQUEST['startRippleId']) : 0;
        $endRippleId = !empty($_REQUEST['endRippleId']) ? $this->getInt($_REQUEST['endRippleId']) : $startRippleId + $pageSize;
        $loadType = !empty($_REQUEST['loadType']) ? $this->getString($_REQUEST['loadType']) : 'latest'; //up|down|latest
        if ($loadType == 'latest') {
            $max = 100;
            $min = ($max - $pageSize) <= $endRippleId ? $endRippleId : $max - $pageSize;
        } elseif ($loadType == 'up') {
            $min = $startRippleId;
            $endRippleId = $endRippleId >= 100 ? 100 : $endRippleId;
            $max = $startRippleId + $pageSize <= $endRippleId ? $startRippleId + $pageSize : $endRippleId;
        } elseif ($loadType == 'down') {
            $max = $startRippleId;
            $endRippleId = $endRippleId >= 0 ? $endRippleId : 0;
            $min = $max - $pageSize < $endRippleId ? $endRippleId : $max - $pageSize;
        }
        for ($i = $max; $i >= $min; $i--) {
            $cell['rippleId'] = $i;
            $temparr[] = $cell;
        }
        
        //初始数据范围（1,100）
        /**
        $temparr = array();
        if ($loadType == 'latest') {
            for ($i = 100; $i >= $i - $pageSize; $i--) {
                $cell['rippleId'] = $i;
                $temparr[] = $cell;
            }
        } elseif ($loadType == 'up') { //加载上面
            $endRippleId = $endRippleId >= 100 ? 100 : $endRippleId;
            $max = $startRippleId + $pageSize <= $endRippleId ? $startRippleId + $pageSize : $endRippleId;
            if ($startRippleId <= 100) {
                for ($i = $startRippleId; $i <= $endRippleId; $i++) {
                    if ($i <= 100) {
                        $cell['rippleId'] = $i;
                        $temparr[] = $cell;
                    }
                }
            }
        } elseif ($loadType == 'down') {//加载下面
        }
        */

        $result = array(
            'result' => $temparr,
            'modify' => array(
                1, 2, 3
            ),
            'deleted' => array(
                8, 9, 10
            )
        );
        $this->sendResult($result);
    }

}
